const chalk = require('chalk')
const dayjs = require('dayjs')
const config = require('../config')
const logger = require('../utils/logger')

const debug = new logger.Logger(null)

function dyeStatus (code) {
    switch (code) {
        case 200: return chalk.green(code)
        case 301: return chalk.yellow(code)
        case 302: return chalk.yellow(code)
        case 404: return chalk.gray(code)
        case 405: return chalk.gray(code)
        case 500: return chalk.red(code)
        default: return chalk.blue(code)
    }
}

function dyeMethod (method) {
    method = method.toUpperCase()

    switch (method) {
        case 'GET': return chalk.green(method)
        case 'POST': return chalk.yellow(method)
        case 'DELETE': return chalk.red(method)
        case 'PUT': return chalk.blue(method)
        case 'OPTIONS': return chalk.gray(method)
        default: return chalk.cyan(method)
    }
}

module.exports = async function (ctx, next) {
    const start = Date.now()
    await next()
    const useTime = Date.now() - start

    !config.isPrd() && debug.log(`[${dayjs().format('HH:mm:ss.SSS')}]`, dyeMethod(ctx.method), ctx.url, dyeStatus(ctx.status), `${chalk.blue(useTime / 1000)} ms`)
}
